package com.kfm.base.function2;

import java.util.Arrays;

public class Demo03 {

    public static void main(String[] args) {
        /*
        给定一个数组，请根据输入在数组的指定位置插入指定的值。
         */
        int[] arr = {1, 2, 3, 4, 5};
        int key = 6;
        int index = 5;

        int[] newArr = insert(arr, index, key);
        System.out.println(Arrays.toString(newArr));
    }

    public static int[] insert(int[] nums, int index, int num){
        if (index >= 0 && index <= nums.length && nums != null){
            int[] newArr = new int[nums.length + 1]; // 新数组

            System.arraycopy(nums, 0, newArr, 0, index);
            newArr[index] = num;
            System.arraycopy(nums, index, newArr, index + 1, nums.length - index);
            return newArr;
        }
        return null;
    }

    public static int[] insert1(int[] nums, int index, int num){
        if (index >= 0 && index <= nums.length && nums != null){
            int[] newArr = new int[nums.length + 1]; // 新数组

            for (int i = 0; i < newArr.length; i++) {
                if (i == index){
                    newArr[i] = num;
                } else if (i < index){
                    newArr[i] = nums[i];
                } else{
                    newArr[i] = nums[i - 1];
                }
            }
            return newArr;
        }
        return null;
    }

}
